

fn main() {
    // 读取输入文件
    let input = fs::read_to_string("input.txt").expect("Failed to read file");

    // 
    let tokens = tokenize(&input);
    let ast = parse(tokens).expect("Failed to parse");
    check_semantics(&ast).expect("Semantic error");

    // 创建LLVM上下文和模块
    let context = unsafe { LLVMContextCreate() };
    let module_name = CString::new("demo_compiler").unwrap();
    let module = unsafe { LLVMModuleCreateWithNameInContext(module_name.as_ptr(), context) };

    // 打印模块
    let ir_string = unsafe { LLVMPrintModuleToString(module) };
    let ir_output = unsafe { std::ffi::CStr::from_ptr(ir_string) }.to_string_lossy();
    println!("{}", ir_output);

    // 清理资源
    unsafe {
        LLVMDisposeMessage(ir_string);
        LLVMDisposeModule(module);
        LLVMContextDispose(context);
    }

    // 创建主函数
    let float_type = unsafe { LLVMFloatTypeInContext(context) };
    let function_type = unsafe { LLVMFunctionType(float_type, ptr::null_mut(), 0, 0) };
    let function_name = CString::new("main").unwrap();
    let function = unsafe { LLVMAddFunction(module, function_name_.as_ptr(), function_type) };


    // 创建基本块
    let entry_name = CString::new("entry").unwrap();
    let basic_block = unsafe { LLVMAppendBasicBlockInContext(context, function, entry_name.as_ptr()) };

    // 生成IR
    let result = generate_llvm_ir(&ast, module, context);

    // 构建返回指令
    let builder = unsafe { LLVMCreateBuilderInContext(context) };
    unsafe {
        LLVMPositionBuilderAtEnd(builder, basic_block);
        LLVMBuildRet(builder, result);
        LLVMDisposeBuilder(builder);
    }
}

